﻿using FlexFlow.Model;
using FlexFlow.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FlexFlow.MVC
{
    /// <summary>
    /// 表示验证类型
    /// </summary>
    public enum AuthType
    {
        /// <summary>
        /// API验证，将会返回Json形式数据
        /// </summary>
        API,
        /// <summary>
        /// 页面方式，将会调用Index页面的needLogin()方法
        /// </summary>
        Page
    }
    /// <summary>
    /// 表示用户验证筛选特性
    /// </summary>
    public class AuthAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 表示验证类型
        /// </summary>
        public AuthType AuthType { get; set; }
        /// <summary>
        /// 构造验证特性
        /// </summary>
        /// <param name="authType">
        /// 验证类型
        /// </param>
        public AuthAttribute(AuthType authType)
        {
            this.AuthType = authType;
        }
        /// <summary> 
        /// 验证权限（action执行前会先执行这里） 
        /// </summary> 
        /// <param name="filterContext"></param> 
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            LoginedUserInfo info = DefaultComponentSettings.OnlineUserPool.GetLoginedUserInfo(filterContext.HttpContext.Request);
            if (info == null)
            {
                if (AuthType == AuthType.Page)
                {
                    ContentResult Content = new ContentResult();
                    Content.Content = "<script type='text/javascript'>needLogin();</script>";
                    filterContext.Result = Content;
                }
                else
                {
                    JsonResult res = new JsonResult();
                    res.Data = new OperateResult()
                    {
                        ResultCode = 400,
                        Message = "拒绝访问！",
                        Tag = "Ulogin"
                    };
                    filterContext.Result = res;
                }
            }
        }
    }
}